// 210. 课程表 II
/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {number[]}
 */
var findOrder = function (numCourses, prerequisites) {
    let indexg = Array(numCourses).fill(0); // 每个节点的入度
    let g = Array(numCourses)
        .fill()
        .map(() => []); // 每个节点的后继节点

    for (let [to, from] of prerequisites) {
        // 构建 上述数据
        g[from].push(to);
        indexg[to]++;
    }
    let q = [];
    // 入度为0的节点入队
    for (let i = 0; i < numCourses; i++) if (indexg[i] == 0) q.push(i);
    let path = [];
    // 构建拓扑排序序列
    while (q.length) {
        let ind = q.shift();
        path.push(ind);
        for (let to of g[ind]) {
            if (--indexg[to] == 0) {
                q.push(to);
            }
        }
    }
    // path长度小于课程数则存在环，输出[]
    return path.length == numCourses ? path : [];
};
